package dao;

import db.MysqlDB;
import vo.Book;
import vo.VO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDao implements IDAO{
    @Override
    public boolean insert(VO vo) {
        Connection conn=null;
        PreparedStatement ps=null;
        MysqlDB db=new MysqlDB();
        int i=0;
        try {
            conn=db.getConn();
            ps=conn.prepareStatement("insert into books values(?,?,?,?,?)");
            Book book=(Book) vo;
            ps.setString(1,book.getId());
            ps.setString(2,book.getTitle());
            ps.setString(3,book.getAuthor());
            ps.setString(4,book.getPress());
            ps.setFloat(5,book.getPric());
            i=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                db.closeAll(conn,ps,null);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return i>0;
    }

    @Override
    public List getAll() {
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List list=new ArrayList();
        MysqlDB db=new MysqlDB();
        try {
            conn=db.getConn();
            ps=conn.prepareStatement("select * from books");
            rs=ps.executeQuery();
            while (rs.next()){
                Book book=new Book();
                book.setId(rs.getString(1));
                book.setTitle(rs.getString(2));
                book.setAuthor(rs.getString(3));
                book.setPress(rs.getString(4));
                book.setPric(rs.getFloat(5));
                list.add(book);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            try {
                db.closeAll(conn,ps,rs);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
